<template>
  <div :style="{ width: width, height: height }">
    <div id="main" :style="{ width: width, height: height, background: background }" ref="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  data() {
    return {
      myChart: {},
      option: {}
    }
  },
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    background: {
      type: String,
      default: '#fff'
    },
    legendData: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    },
    colorList: {
      type: Array,
      default: () => []
    },
    name: {
      type: String,
      default: ''
    }
  },
  mounted() {
    // 初始化chart
    this.$nextTick(() => {
      this.myChart = echarts.init(this.$refs.chart)
    })
  },

  methods: {
    // 初始化动态加载chart
    init() {
      var seriesData = this.seriesData
      if (seriesData.length < 0) return []
      var series = []
      var data = []
      seriesData.forEach((el, i) => {
        // 最后一个是折线
        data.push({
          value: el.value,
          name: el.name,
          label: {
            color: this.colorList[i]
          }
        })
      })
      series.push({
        name: this.name,
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: data,
        color: this.colorList,
        labelLine: {
          show: false,
          length: 1
        },
        avoidLabelOverlap: true,
        itemStyle: {
          normal: {
            label: {
              show: true,
              formatter: '{b}\n {d}%'
            }
          },
          labelLine: { show: true }
        }
      })
      return series
    },
    // 初始化统计图
    drawChart() {
      var that = this
      this.myChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          data: this.legendData,
          top: '2%'
        },
        series: this.init()
      })
      this.option && this.myChart.setOption(this.option)
      window.onresize = () => {
        this.myChart.resize()
      }
    }
  }
}
</script>

<style></style>
